import 'dart:async';
import 'dart:developer';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/sv_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';

class UpdateVersionBloc implements BlocBase {
  String _type = '';
  StreamController<Object> _initController = StreamController<Object>();
  StreamSink get initDate => _initController.sink;

  UpdateVersionBloc() {
    _initController.stream.listen(initData);
  }

  void initData(data) {
    if (data is String) {
      _type = data;
    }
    _initTask(data);
  }

  void _initTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext).requestFocus(FocusNode());
    if ('person' == _type) {
      BotToast.showLoading();
    }
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.VERSION_URL, data: data, headers: {}, success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            SvEntity params = SvEntity.fromJson(result);

            //这里去更新版本
            HttpUtilAll.post(Apis.INSTALL_URL, data: data, headers: {}, success: (result) {
              //这里去更新版本
              if ('person' == _type) {
                eventBus.fire(NewVersionEvent(params.val, result["val"], result["name"]));
              } else {
                eventBus.fire(UdateVersionEvent(params.val, result["val"], result["name"]));
              }
            }, error: (errorMsg) {
              BotToast.closeAllLoading();
              // 请求失败返回的错误信息
              BotToast.showText(text: errorMsg);
            });
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _initController?.close();
  }
}
